package com.jz.community.moduleshopping.integralGoods.ui;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.base.BaseX5WebActivity;
import com.jz.community.basecomm.constant.HtmlConstant;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.BaseUserUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.integralGoods.adapter.IntegralCouponAdapter;
import com.jz.community.moduleshopping.integralGoods.bean.IntegralCouponInfo;
import com.jz.community.moduleshopping.integralGoods.bean.IntegralExchangeCouponInfo;
import com.jz.community.moduleshopping.integralGoods.bean.IntegralInfo;
import com.jz.community.moduleshopping.integralGoods.bean.SignDataBean;
import com.jz.community.moduleshopping.integralGoods.task.GetIntegralCouponTask;
import com.jz.community.moduleshopping.integralGoods.task.GetIntegralTask;
import com.jz.community.moduleshopping.integralGoods.task.IntegralExchangeTask;
import com.jz.community.moduleshopping.integralGoods.task.SignTask;
import com.jz.community.moduleshopping.integralGoods.ui.view.IntegralCouponExchangePop;
import com.jz.community.moduleshopping.integralGoods.ui.view.WrapContentHeightViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Tony.Fan on 2018/6/26 09:41
 * 积分商城
 */
@Route(path = RouterIntentConstant.INTEGRAL_GOODS)
public class IntegralHomeActivity extends BaseMvpActivity {

    @BindView(R2.id.title_back_left)
    ImageView titleBackLeft;
    @BindView(R2.id.title_name)
    TextView titleName;
    @BindView(R2.id.title_right)
    TextView titleRight;
    @BindView(R2.id.title_toolbar)
    Toolbar titleToolbar;
    @BindView(R2.id.integral_tab_layout)
    SlidingTabLayout integralTabLayout;
    @BindView(R2.id.integral_viewpager)
    WrapContentHeightViewPager integralViewpager;
    @BindView(R2.id.integral_coupon_recyclerView)
    RecyclerView integralCouponRecyclerView;
    @BindView(R2.id.integral_point_iv)
    ImageView integralPointIv;
    @BindView(R2.id.usable_point_name_tv)
    TextView usablePointNameTv;
    @BindView(R2.id.usable_point_tv)
    TextView usablePointTv;
    @BindView(R2.id.integral_point_layout)
    RelativeLayout integralPointLayout;
    @BindView(R2.id.integral_coupon_history_tv)
    TextView integralCouponHistoryTv;
    @BindView(R2.id.integral_sign_iv)
    ImageView integralSignIv;
    @BindView(R2.id.title_right_iv)
    ImageView titleRightIv;
    @BindView(R2.id.integral_goods_more_layout)
    LinearLayout integralGoodsMoreLayout;
    @BindView(R2.id.integral_exchange_coupon_layout)
    LinearLayout integralExchangeCouponLayout;
    @BindView(R2.id.integral_NestedScrollView)
    ScrollView integral_NestedScrollView;
    private String[] titles = {"0-499", "500-1999", "2000以上"};
    private IntegralCouponAdapter integralGoodsAdapter;
    private IntegralGoodsFragment integralGoodsFragment;
    private List<Fragment> fragments = new ArrayList<>();
    private int pageInPos = 1;

    @Override
    protected void initView() {
        super.initView();
        initTitle("积分商城", "");
        setImmersionBar(titleToolbar);
        titleRightIv.setImageResource(R.mipmap.integral);
        SHelper.vis(titleRightIv);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_shopping_integral_home_goods_layout;
    }

    @Override
    protected void addListener() {
        super.addListener();
        titleRightIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(mActivity, BaseX5WebActivity.class);
                mIntent.putExtra("url", HtmlConstant.INTEGRAL_HTML_URL);
                mIntent.putExtra("title", "积分规则");
                startActivity(mIntent);
            }
        });
        integralCouponHistoryTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(IntegralHomeActivity.this, IntegralExchangeHistoryActivity.class));
            }
        });
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        getIntegralCouponInfo();
        initViewPager();
    }

    private void initViewPager() {
        FragmentStatePagerAdapter viewPagerAdapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {

            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return titles.length;
            }

            @Override
            public int getItemPosition(Object object) {
                return PagerAdapter.POSITION_NONE;
            }
        };

        for (int i = 0; i < titles.length; i++) {
            integralGoodsFragment = IntegralGoodsFragment.newInstance(i + 1);
            fragments.add(integralGoodsFragment);
        }
        integralViewpager.setOffscreenPageLimit(3);
        integralViewpager.setAdapter(viewPagerAdapter);
        integralTabLayout.setViewPager(integralViewpager, titles);

        integralTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                pageInPos = (position + 1);
                integral_NestedScrollView.scrollTo(0, 10);// 改变滚动条的位置
                integralGoodsFragment.setDisPriceType(pageInPos);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    /**
     * 用户积分
     */
    private void getIntegralDatas() {
        if (BaseUserUtils.getIsLogin(this)) {
            new GetIntegralTask(this, o -> {
                IntegralInfo integralInfo = (IntegralInfo) o;
                if (!Preconditions.isNullOrEmpty(integralInfo) && !Preconditions.isNullOrEmpty(integralInfo.get_embedded().getContent())) {
                    String userIntegral = integralInfo.get_embedded().getContent().get(0).getResidualIntegral();
                    usablePointTv.setText(userIntegral);
                    BaseSpUtils.getInstance().setIntegralNum(this, ConverterUtils.toInt(userIntegral));
                }
            }).execute("0");
        } else {
            usablePointTv.setText("0");
        }
    }

    private void getIntegralCouponInfo() {
        if (BaseUserUtils.getIsLogin(this)) {
            new GetIntegralCouponTask(this, new ITaskCallbackListener() {
                @Override
                public void doTaskComplete(Object o) {
                    IntegralCouponInfo integralCouponInfo = (IntegralCouponInfo) o;
                    if (!Preconditions.isNullOrEmpty(integralCouponInfo)) {
                        SHelper.vis(integralExchangeCouponLayout);
                        IntegralCouponInfo.EmbeddedBean embeddedBean = integralCouponInfo.get_embedded();
                        handleBindAdapter(embeddedBean);
                    } else {
                        SHelper.gone(integralExchangeCouponLayout);
                    }
                }
            }).execute("0");
        } else {
            SHelper.gone(integralExchangeCouponLayout);
        }
    }

    private void handleBindAdapter(IntegralCouponInfo.EmbeddedBean embeddedBean) {
        if (integralGoodsAdapter == null) {
            GridLayoutManager main_layoutManager = new GridLayoutManager(this, 2);
            integralCouponRecyclerView.setLayoutManager(main_layoutManager);
            integralGoodsAdapter = new IntegralCouponAdapter(embeddedBean.getContent());
            integralGoodsAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
            integralCouponRecyclerView.setAdapter(integralGoodsAdapter);
            integralGoodsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if (view.getId() == R.id.integral_btn) {
                        integralCouponPop(embeddedBean, position);
                    }
                }
            });
            integralGoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    integralCouponPop(embeddedBean, position);
                }
            });
        } else {
            integralGoodsAdapter.addData(embeddedBean.getContent());
        }
    }

    /**
     * 领卷弹窗
     *
     * @param embeddedBean
     * @param position
     */
    private void integralCouponPop(IntegralCouponInfo.EmbeddedBean embeddedBean, int position) {
        IntegralCouponExchangePop integralCouponExchangePop = new IntegralCouponExchangePop(this, integralPointLayout);
        integralCouponExchangePop.handleShowData(embeddedBean.getContent(), position);
        integralCouponExchangePop.setIntegralCouponListener(new IntegralCouponExchangePop.IntegralCouponListener() {
            @Override
            public void integralCouponResult() {
                IntegralExchangeCouponState(embeddedBean.getContent().get(position).getId() + "", position);
            }
        });
    }

    /**
     * 领卷兑换
     *
     * @param couponId
     */
    private void IntegralExchangeCouponState(String couponId, int position) {
        new IntegralExchangeTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                IntegralExchangeCouponInfo integralExchangeCouponInfo = (IntegralExchangeCouponInfo) o;
                if (!Preconditions.isNullOrEmpty(integralExchangeCouponInfo.getCouponInfo())) {
                    integralGoodsAdapter.getData().get(position).setExchange(1);
                    WpToast.l(IntegralHomeActivity.this, "兑换成功");
                    integralGoodsAdapter.notifyDataSetChanged();
                } else {
                    WpToast.l(IntegralHomeActivity.this, integralExchangeCouponInfo.getMessage());
                }
            }
        }).execute(couponId);
    }

    @OnClick(R2.id.integral_btn)
    public void integralGoodsMoreLayoutClick() {
        startActivity(new Intent(this, IntegralGoodsActivity.class).putExtra("disType", pageInPos));
    }

    @OnClick(R2.id.integral_sign_iv)
    public void integralSignIvClick() {
        RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.SIGN);
    }

    @OnClick(R2.id.integral_point_layout)
    public void integralPointLayoutClick() {
        if (BaseUserUtils.showIsLoginDialog(this)) {
            RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MY_INTEGRAL);
        }
    }

    /**
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EventBus(AppEvent message) {
        if (message.tag == EventConfig.REFRESH_SIGN) {
            integralSignIv.setImageResource(R.mipmap.integral_already_sign);
            integralSignIv.setEnabled(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getIntegralDatas();
        updateSignState();
    }

    private void updateSignState() {
        if (BaseSpUtils.getInstance().getIsSign(this)) {
            new SignTask(this, o -> {
                SignDataBean signInfo = (SignDataBean) o;
                if (!Preconditions.isNullOrEmpty(signInfo) && !Preconditions.isNullOrEmpty(signInfo.getStatus())) {
                    if (!RxDataTool.isNullString(signInfo.getStatus())) {
                        //今天是否已签到
                        if (signInfo.getStatus().equals("0")) {
                            integralSignIv.setImageResource(R.mipmap.integral_sign);
                            integralSignIv.setEnabled(false);
                        } else if (signInfo.getStatus().equals("1")) {
                            //已签到
                            integralSignIv.setImageResource(R.mipmap.integral_already_sign);
                            integralSignIv.setEnabled(false);
                        }
                    }
                }
            }).execute();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }
}
